namespace RAYTRACING {
    /**
     * 绘制器
     */
    export class Painter {
        private static readonly _helpBlackColor: Color32 = Color32.Black();
        private static readonly _helpWhiteColor: Color32 = Color32.White();
        private _ctx: CanvasRenderingContext2D;
        constructor(ctx: CanvasRenderingContext2D) {
            this._ctx = ctx;
        }

        /** 清理帧 */
        public clearFrame(clearColor: string = "#ffffff") {
            let _ctx = this._ctx;
            let canvas = _ctx.canvas;
            _ctx.fillStyle = clearColor;
            _ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        /**
         * 绘制一个像素点到指定位置(canvas 坐标系原点是左上)
         * @param x canvas坐标x
         * @param y canvas坐标y
         * @param color 像素点颜色
         * @param size 大小
         */
        public drawPoint(x: number, y: number, color: string = "#ffffff", size: number = 1) {
            let _ctx = this._ctx;
            _ctx.fillStyle = color;
            if (size < 1) size = 1;
            if (size != 1) {
                let _s = Math.floor(size * 0.5);
                x -= _s;
                y -= _s;
                if (x < 0) x = 0;
                if (y < 0) y = 0;
            }
            //
            _ctx.fillRect(x, y, size, size);
        }

        /**
         * 绘制一帧画面
         * @param frameData 
         */
        public drawFrame(frameData: Uint8Array[][]) {
            let _ctx = this._ctx;
            if (!_ctx || !frameData || !frameData[0]) return;
            let canvas = _ctx.canvas;
            let w = Math.min(canvas.width, frameData[0].length);
            let h = Math.min(canvas.height, frameData.length);
            for (let y = 0; y < h; y++) {
                let row = frameData[y];
                for (let x = 0; x < w; x++) {
                    _ctx.fillStyle = Uint8ArraytoCSS(row[x]);
                    _ctx.fillRect(x, y, 1, 1);
                }
            }
        }

        /**
         * 绘制一帧画面
         * @param frameData 
         * @param width 
         * @returns 
         */
        public drawFrameW(frameData: Uint8Array[], width: number) {
            let _ctx = this._ctx;
            if (!_ctx || !frameData || !frameData[0]) return;
            let canvas = _ctx.canvas;
            let w = Math.min(canvas.width, width);
            let h = Math.min(canvas.height, frameData.length / width);
            let c = 0;
            for (let y = 0; y < h; y++) {
                for (let x = 0; x < w; x++) {
                    _ctx.fillStyle = Uint8ArraytoCSS(frameData[c]);
                    _ctx.fillRect(x, y, 1, 1);
                    c++;
                }
            }
        }
    }
}